<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools show-before>
        <template v-slot:before>
          <span>共{{ page.total }}条记录</span>
        </template>
        <template v-slot:after>
          <el-button size="small" type="warning" @click="handleNavigateImport">导入</el-button>
          <el-button size="small" type="danger" :loading="exportloading" @click="handleExportExcelData">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <!-- 放置表格和分页 -->
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" sortable="" prop="username">
            <template v-slot="{row}">
              <img
                v-imageerror="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                style="border-radius: 50%; width: 100px; height:100px;"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot="{row}">
              {{ row.timeOfEntry| formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" align="center" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="handleEditRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :current-page="page.page"
            :page-size="page.size"
            :total="page.total"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <add-employee :show-dialog.sync="showDialog" @addEmployee="getEmployeeList" />
    <!-- 展示头像二维码信息 -->
    <el-dialog title="二维码" :visible.sync="showQrcodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>
    <!-- 权限分配弹框 -->
    <assign-role ref="AssignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import AddEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
import { formatDate } from '@/filters/index' // 导入过滤器那个方法
// 生成二维码插件
import Qrcode from 'qrcode'
export default {
  components: { AddEmployee, AssignRole },
  data() {
    return {
      list: [],
      loading: false,
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      showDialog: false,
      exportloading: false,
      showQrcodeDialog: false,
      showRoleDialog: false,
      userId: '' // 点击角色获取当前的用户id
    }
  },
  mounted() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      this.loading = true
      const { rows, total } = await getEmployeeList(this.page)
      this.loading = false
      this.list = rows
      this.page.total = total
    },
    handleCurrentChange(page) {
      this.page.page = page
      this.getEmployeeList()
    },
    // 聘用形式的格式化
    formatEmployment(row, column, cellValue, index) {
      const itemRow = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return itemRow ? itemRow.value : '未知'
    },
    // 点击删除员工数据
    async delEmployee(employeeId) {
      try {
        await this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await delEmployee(employeeId)
        this.$message.success('删除成功')
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },
    // 点击导入员工数据
    handleNavigateImport() {
      this.$router.push({ path: '/import' })
    },
    handleExportExcelData() {
      // 导出员工数据
      // npm install xlsx file-saver -S
      // npm install script-loader -S -D ==> 支持懒加载形式
      // 在 `js-xlsx`的基础上又封装了[Export2Excel.js](https://github.com/PanJiaChen/vue-element-admin/blob/master/src/vendor/Export2Excel.js)来方便导出数据。
      // 由于`js-xlsx`体积还是很大的，导出功能也不是一个非常常用的功能，所以使用的时候建议使用懒加载。使用方法如下：
      // 创建一个vendor/Export2Excel文件

      // import('@/vendor/Export2Excel').then(excel => {
      //   excel.export_json_to_excel({
      //     header: tHeader, // 表头 必填[]
      //     data, [] // 具体数据 必填 [[]]
      //     filename: 'excel-list', // 非必填
      //     autoWidth: true, // 非必填(自适应)
      //     bookType: 'xlsx' // 非必填
      //   })
      // })
      this.exportloading = true
      import('@/vendor/Export2Excel').then(async excel => {
        const headers = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        // 获取列表所有数据
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        // 导出表格数据(获取数据总数条数)
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data: this.formatJSON(headers, rows), // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
        this.exportloading = false
      })
    },
    formatJSON(headers, rows) {
      return rows.map(item => {
        return Object.keys(headers).map(key => {
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]]) // 返回格式化之前的时间
          } else if (headers[key] === 'formOfEmployment') {
            var en = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return en ? en.value : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    // 点击头像展示头像二维码
    showQrCode(url) {
      if (!url) return this.$message.warning('该用户还未上传头像')

      this.showQrcodeDialog = true
      // 这个时候二维码不能正常展示?
      // 因为this.showQrcodeDialog = true 使页面进行更新(但是页面更新是异步的)
      // 需要等到上次视图更新完成在操作, 所以需要借用this.nextTick()
      this.$nextTick(() => {
        Qrcode.toCanvas(this.$refs.myCanvas, url)
      })
    },
    // 点击编辑角色按钮
    async handleEditRole(id) {
      // 通过获取组件实例去调用子组件方法
      this.userId = id
      await this.$refs.AssignRole.getUserDetailById(id)
      this.showRoleDialog = true // 获取数据完成后再显示弹框, 解决数据闪烁的问题
    }
  }
}
</script>

<style>

</style>
